package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.ColorMatrixColorFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.alibaba.fastjson.JSON;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.BabyPhotoCloudAdapter;
import com.jdy.haoduoai.adapter.BabyPhotoCloudAdapter.ButtonClickListener;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.ImageItem;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PhotoInfoAlbum;
import com.jdy.haoduoai.model.PhotoInfoAlbumWrapper;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.jdy.haoduoai.pulltorefresh.PullableListView;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.CustomConstants;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageFetcherMine;
import com.jdy.haoduoai.util.ImageUtils;
import com.jdy.haoduoai.util.IntentConstants;
import com.jdy.haoduoai.util.PathUtil;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.RoundImageView;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;

/**
 * 云相册
 * 
 * @author Administrator
 * 
 */
@SuppressLint("InflateParams")
public class BabyPhotoCloudActivity extends BaseActivity implements
    OnClickListener, ButtonClickListener {

  @InjectView(id = R.id.task_views, click = true)
  private PullableListView task_views;
  @InjectView(id = R.id.refresh_view, click = true)
  private PullToRefreshLayout refreshLayout1;

  @SuppressWarnings("unused")
  private View refresh_head, load_more;
  private boolean isEditable;

  private ImageView img_watchbaby, img_back;
  private com.jdy.haoduoai.view.RoundImageView img_babyavatar;
  private Bitmap mScaleCrop;

  private final static int REQUEST_WALL_PIC = 100;
  private final static int REQUEST_PUBLISH_PIC = 101;

  @InjectView(id = R.id.img_headbg)
  private ImageView img_headbg;
  @InjectView(id = R.id.img_bg)
  private ImageView img_bg;
  @InjectView(id = R.id.rel_todayclick, click = true)
  private View rel_todayclick;
  @InjectView(id = R.id.playbackryl)
  private RelativeLayout playbackryl;

  private TextView tv_photonum, tv_age;
  private int mLastPage = 1;
  private String wall_pic;
  public static List<ImageItem> mDataList = new ArrayList<ImageItem>();
  private int albumId, posi;
  private ArrayList<PhotoInfoAlbum> mList = new ArrayList<PhotoInfoAlbum>();
  private ArrayList<PhotoInfoAlbum> mAdapterList = new ArrayList<PhotoInfoAlbum>();

  private BabyPhotoCloudAdapter mBabyPhotoCloudAdapter;
  public final float[] BT_SELECTED = new float[] { 1, 0, 0, 0, -50, 0, 1, 0, 0,
      -50, 0, 0, 1, 0, -50, 0, 0, 0, 1, 0 };

  @SuppressWarnings("unused")
  private ImageFetcherMine mHelper;
  private View mHeader;

  private static class DialogHolder {
    public Dialog dialog;
    public EditText editText;
    @SuppressWarnings("unused")
    public TextView tv_send, tv_cancel;
  }

  private DialogHolder dialogHolder;

  private void sendContentRequest(final String content) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, final ResponseResult arg0) {

        if (arg0.isSuccess()) {
          mBabyPhotoCloudAdapter.updataView(posi, task_views, content);
        } else {
          toastShow(arg0.data);
        }

        dismissLoading();

        if (dialogHolder != null && dialogHolder.dialog != null) {
          dialogHolder.dialog.dismiss();
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put("title", content);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/member/photocloud/" + albumId, param_,
            HttpUtils.TAG_PUT_REQUEST);
      }
    }).execute();
  }

  private void setupDialog() {
    dialogHolder = new DialogHolder();

    Dialog mUserInputDialog = new Dialog(this, R.style.MyDialogStyleBottom);
    mUserInputDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mUserInputDialog.setCancelable(true);
    mUserInputDialog.setCanceledOnTouchOutside(false);

    final LinearLayout layout = (LinearLayout) LayoutInflater.from(this)
        .inflate(R.layout.widget_input_coupon_code, null);
    final EditText editext = (EditText) layout.findViewById(R.id.edit_code);

    // 发送
    final TextView btn_action = (TextView) layout.findViewById(R.id.btn_action);
    btn_action.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        final String code = editext.getText().toString();

        if (Tools.isNotEmpty(code)) {
          sendContentRequest(code);
        } else {
          toastShow("请输入内容");
        }
      }
    });

    // 取消
    final TextView btn_cancel = (TextView) layout.findViewById(R.id.btn_cancel);
    btn_cancel.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        dialogHolder.dialog.dismiss();
      }
    });

    editext.setOnEditorActionListener(new OnEditorActionListener() {
      @Override
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
          final String code = editext.getText().toString();
          if (!Tools.isEmpty(code)) {
            sendContentRequest(code);
            closeInputMethod(editext.getWindowToken());
          } else {
            toastShow("请输入内容");
            dialogHolder.dialog.dismiss();
          }
          return true;
        }
        return false;
      }
    });
    LayoutParams param4 = new LayoutParams(-1, -1);
    param4.gravity = Gravity.BOTTOM;
    mUserInputDialog.addContentView(layout, param4);

    Window dialogWindow = mUserInputDialog.getWindow();
    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
    lp.width = -1;
    dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
    dialogWindow.setAttributes(lp);

    dialogHolder.dialog = mUserInputDialog;
    dialogHolder.editText = editext;
    dialogHolder.tv_send = btn_action;
    dialogHolder.tv_cancel = btn_cancel;
  }

  private void openCodeInputDialog(String code) {
    dialogHolder.editText.setText(code);
    dialogHolder.dialog.show();

    handler.sendEmptyMessageDelayed(0, 60);
  }

  @SuppressLint("HandlerLeak")
  private final Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
      if (msg.what == 0) {
        dialogHolder.editText.requestFocus();
        openInputMethod(dialogHolder.editText);
      } else {
        closeInputMethod(dialogHolder.editText.getWindowToken());
      }
    }
  };

  @SuppressWarnings("unused")
  private void deleteCloudPhoto(final ImageItem item,
      final ArrayList<ImageItem> list) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, final ResponseResult arg0) {
        if (arg0.isSuccess()) {

        } else {
          toastShow(arg0.data);
        }

        list.remove(item);
        mBabyPhotoCloudAdapter.notifyDataSetChanged();

        dismissLoading();
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/member/photocloud/" + item.id, param_,
            HttpUtils.TAG_DELETE_REQUEST);
      }
    }).execute();
  }

  @Override
  @SuppressLint({ "InflateParams", "ClickableViewAccessibility" })
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.baby_photocloud2);

    hideTitleView();

    mHelper = ImageFetcherMine.getInstance(getApplicationContext());

    mHeader = View.inflate(this, R.layout.photo_header, null);

    img_headbg = (ImageView) mHeader.findViewById(R.id.img_headbg);
    img_bg = (ImageView) mHeader.findViewById(R.id.img_bg);
    rel_todayclick = mHeader.findViewById(R.id.rel_todayclick);

    img_headbg.setOnClickListener(this);
    img_bg.setOnClickListener(this);
    rel_todayclick.setOnClickListener(this);

    task_views = (PullableListView) findViewById(R.id.task_views);
    img_babyavatar = (RoundImageView) mHeader.findViewById(R.id.img_babyavatar);
    img_watchbaby = (ImageView) mHeader.findViewById(R.id.img_watchbaby);
    tv_photonum = (TextView) mHeader.findViewById(R.id.tv_photonum);
    tv_age = (TextView) mHeader.findViewById(R.id.tv_age);
    tv_age.setText(LeXiaoXiaoBanApp.getInstance().kidAge);
    img_back = (ImageView) mHeader.findViewById(R.id.back);
    img_watchbaby.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    img_back.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

    img_watchbaby.setOnClickListener(this);
    img_back.setOnClickListener(this);
    img_babyavatar.setOnClickListener(this);
    setupDialog();

    task_views.addHeaderView(mHeader);

    refreshLayout1.setOnRefreshListener(new OnRefreshListener() {

      @Override
      public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        mLastPage++;
        // isrefreshlist1 = false;

        loadInfo();
      }

      @Override
      public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        refreshLayout1.changeState(0);
      }
    });

    showloading("");
    loadInfo();
  }

  private PhotoInfoAlbumWrapper mPhotoInfoAlbumWrapper;

  private void loadInfo() {

    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, final ResponseResult arg0) {

        if (arg0.isSuccess()) {
          if (Tools.isNotEmpty(arg0.data)) {
            mPhotoInfoAlbumWrapper = JsonSerializer.getInstance().deserialize(
                arg0.data, PhotoInfoAlbumWrapper.class);

            if (Tools.isNotEmpty(mPhotoInfoAlbumWrapper.wall_pic)) {
              wall_pic = mPhotoInfoAlbumWrapper.wall_pic;
            }

            if (mAdapterList != null) {
              mAdapterList.clear();
            }

            mAdapterList = mPhotoInfoAlbumWrapper.data;
            if (Tools.isNotEmpty(mAdapterList)) {
              mList.addAll(mAdapterList);
            }

            if (!mList.isEmpty()) {
              setView();
            } else {
              if (mBabyPhotoCloudAdapter == null) {
                mBabyPhotoCloudAdapter = new BabyPhotoCloudAdapter(
                    BabyPhotoCloudActivity.this, mList);

                mBabyPhotoCloudAdapter
                    .setButtonClickListener(BabyPhotoCloudActivity.this);
              } else {
                mBabyPhotoCloudAdapter.updateData(mList);
              }

              task_views.setAdapter(mBabyPhotoCloudAdapter);
              mBabyPhotoCloudAdapter.notifyDataSetChanged();
            }

            if (mList != null && mList.size() == mPhotoInfoAlbumWrapper.total) {
              refreshLayout1.refreshFinish(PullToRefreshLayout.LOAD_COMPLETED);
              refreshLayout1.loadmoreFinish(PullToRefreshLayout.LOAD_COMPLETED);
            } else {
              refreshLayout1.refreshFinish(PullToRefreshLayout.SUCCEED);
              refreshLayout1.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            }

          }
        } else {
          toastShow(arg0.data);
        }

        // if (mPhotoInfoAlbumWrapper.pic_count > 0) {
        // tv_photonum.setText("照片" + mPhotoInfoAlbumWrapper.pic_count + "张");
        // }

        if (mLastPage == 1) {
          tv_photonum.setText("照片" + mPhotoInfoAlbumWrapper.pic_count + "张");
        }

        if (Tools.isNotEmpty(wall_pic)) {
          Picasso.with(BabyPhotoCloudActivity.this).load(wall_pic)
              .into(img_babyavatar);
          Picasso.with(BabyPhotoCloudActivity.this).load(wall_pic).into(img_bg);
          img_bg.setColorFilter(new ColorMatrixColorFilter(BT_SELECTED));
        }

        if (mLastPage > 1) {
          task_views.setSelection(task_views.getCount() - 1);
        }

        dismissLoading();
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put("pagesize", String.valueOf(10));
        param_.put("page", mLastPage);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/member/photocloud", param_, HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void setView() {
    if (mBabyPhotoCloudAdapter == null) {
      mBabyPhotoCloudAdapter = new BabyPhotoCloudAdapter(this, mList);
      mBabyPhotoCloudAdapter.setButtonClickListener(this);
    } else {
      mBabyPhotoCloudAdapter.updateData(mList);
    }

    task_views.setAdapter(mBabyPhotoCloudAdapter);
    mBabyPhotoCloudAdapter.notifyDataSetChanged();
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
      Intent returnedIntent) {
    super.onActivityResult(requestCode, resultCode, returnedIntent);
    switch (requestCode) {
    case REQUEST_WALL_PIC:
      if (resultCode == RESULT_OK) {
        Uri wallpicUri = Uri.parse(returnedIntent.getExtras()
            .getString("image"));
        setImageViewContent(img_babyavatar, wallpicUri);
        uploadWallPic(wallpicUri.getPath());
      }
      break;

    case REQUEST_PUBLISH_PIC:

      if (resultCode == RESULT_OK) {
        mLastPage = 1;
        // if (mAdapterList != null) {
        // mAdapterList.clear();
        // }
        // if (mList != null) {
        // mList.clear();
        // }
        // loadInfo();

        if (mAdapterList != null) {
          mAdapterList.clear();
        }
        if (mList != null) {
          mList.clear();
        }

        task_views.removeHeaderView(mHeader);
        task_views.addHeaderView(mHeader);

        mLastPage = 1;
        showloading("");
        loadInfo();

      }

      break;

    }
  }

  private void uploadWallPic(final String filePath) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, final ResponseResult result) {
        if (result != null && result.isSuccess()) {
          new CustomAsyncTask(BabyPhotoCloudActivity.this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity,
                final ResponseResult result) {
              if (result != null && result.isSuccess()) {
                toastShow("更新成功");
              }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
              LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
              HashMap<String, Object> param_ = new HashMap<String, Object>();
              param_.put(HttpUtils.TAG_SNO_I, lu.sno);
              // param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
              param_.put("url", result.data);

              return HttpUtils.startRequest(HttpUtils.API_URL
                  + "/api/2.0/member/photocloud/update_photowall", param_,
                  HttpUtils.TAG_POST_REQUEST);

            }
          }).execute("请检查网络连接!");
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_MOBILE_I, lu.id);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_MODULE_I, "member/photowall");

        return HttpUtils.startUploadRequest(HttpUtils.API_URL
            + HttpUtils.UPLOAD_BABY_AVATAR_POST, param_, "Filedata", filePath,
            HttpUtils.TAG_POST_REQUEST);

      }
    }).execute("请检查网络连接!");
  }

  private static final int REQUIRED_WIDTH = 300;
  private static final int REQUIRED_HEIGHT = 300;

  private Bitmap setImageViewContent(ImageView source, Uri original) {
    if (original != Uri.EMPTY) {
      Bitmap originalBitmap = ImageUtils.getBitmapFromUri(this, original);
      if (originalBitmap != null) {
        img_bg.setImageBitmap(originalBitmap);

        Bitmap bm = ImageUtils.scaleCropToFit(originalBitmap, REQUIRED_WIDTH,
            REQUIRED_HEIGHT, true);
        source.setImageURI(null);
        if (bm != null) {
          source.setImageBitmap(bm);

        }
        return bm;
      }
    }
    return null;
  }

  @Override
  public void onClick(View v) {
    Intent intent = new Intent();

    switch (v.getId()) {
    case R.id.img_babyavatar:
      intent.setClass(this, SelectPicPopupWindow.class);
      intent.putExtra("avatar_path",
          PathUtil.getWallPicPath(getApplicationContext()));
      startActivityForResult(intent, REQUEST_WALL_PIC);
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      break;
    case R.id.rel_todayclick:
      intent.setClass(this, PublishActivity.class);
      startActivityForResult(intent, REQUEST_PUBLISH_PIC);
      break;
    case R.id.img_edit:
      isEditable = !isEditable;

      if (isEditable) {

        // photo_relativeLayout.setVisibility(View.VISIBLE);
      }

      mBabyPhotoCloudAdapter.setEditMode(isEditable);
      // mBabyPhotoCloudAdapter.notifyDataSetChanged();

      break;

    // case R.id.tv_edit:
    // isEditable = !isEditable;
    //
    // if (!isEditable) {
    //
    // // photo_relativeLayout.setVisibility(View.GONE);
    // } /*
    // * else { tv_edit.setVisibility(View.GONE);
    // * img_edit.setVisibility(View.VISIBLE);
    // * photo_relativeLayout.setVisibility(View.GONE); }
    // */
    //
    // mBabyPhotoCloudAdapter.setEditMode(isEditable);
    // // mBabyPhotoCloudAdapter.notifyDataSetChanged();
    //
    // break;
    case R.id.back:
      finish();
      break;
    // case R.id.img_babyavatar:
    // break;
    case R.id.img_watchbaby:
//      intent.setClass(this, VideoViewDemo.class);
//      startActivity(intent);
      break;

    // case R.id.img_seelocalalbum:
    // Intent intent2 = new Intent(this, ImageBucketChooseActivity.class);
    // intent2.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE,
    // getAvailableSize());
    // startActivity(intent2);
    //
    // break;
    default:
      break;
    }
  }

  @Override
  public void onPause() {
    super.onPause();

    saveTempToPref();
  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveTempToPref();
  }

  @SuppressWarnings({ "unused", "unchecked" })
  private void initData() {
    getTempFromPref();
    List<ImageItem> incomingDataList = (List<ImageItem>) getIntent()
        .getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
    if (incomingDataList != null) {
      mDataList.addAll(incomingDataList);
    }
  }

  @SuppressWarnings("unused")
  private void removeTempFromPref() {
    SharedPreferences sp = getSharedPreferences(
        CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
    sp.edit().remove(CustomConstants.PREF_TEMP_IMAGES).commit();
  }

  private void getTempFromPref() {
    SharedPreferences sp = getSharedPreferences(
        CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
    String prefStr = sp.getString(CustomConstants.PREF_TEMP_IMAGES, null);
    if (!TextUtils.isEmpty(prefStr)) {
      List<ImageItem> tempImages = JSON.parseArray(prefStr, ImageItem.class);
      mDataList = tempImages;
    }
  }

  private void saveTempToPref() {
    SharedPreferences sp = getSharedPreferences(
        CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
    String prefStr = JSON.toJSONString(mDataList);
    sp.edit().putString(CustomConstants.PREF_TEMP_IMAGES, prefStr).commit();

  }

  private int getAvailableSize() {
    int availSize = CustomConstants.MAX_IMAGE_SIZE - mDataList.size();
    if (availSize >= 0) {
      return availSize;
    }
    return 0;
  }

  @Override
  public void onEditClicked(int id, int pos) {
    albumId = id;
    posi = pos;
    openCodeInputDialog("");
  }

  @Override
  public void onShareClicked(int id) {
    Intent intent = new Intent(this, SharePopupWindow.class);
    intent.putExtra("Sharedlink",
        "http://www.xiaoxiaoban.com.cn/shareAlbum_hda/shareAlbum.html?pid=" + id);
    startActivity(intent);
  }
}
